package com.example.aiquantong.androidopengles;

import android.opengl.GLES20;
import android.os.Environment;
import android.os.Bundle;
import android.os.Build;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ConfigurationInfo;

import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import android.graphics.*;

import android.opengl.GLSurfaceView;

import javax.microedition.khronos.opengles.GL10;

import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.nio.IntBuffer;

import  java.io.*;

import  android.annotation.TargetApi;


public class MainActivity extends AppCompatActivity {
    static String tag = "MainActivity";
    private GLSurfaceView mGLSurfaceView;
    private Button mButton;

    protected boolean shouldAskPermissions() {
        return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
    }

    @TargetApi(23)
    protected void askPermissions() {
        String[] permissions = {
                "android.permission.READ_EXTERNAL_STORAGE",
                "android.permission.WRITE_EXTERNAL_STORAGE"
        };
        int requestCode = 200;
        requestPermissions(permissions, requestCode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (shouldAskPermissions()) {
            askPermissions();
        }

        setContentView(R.layout.activity_main);

        mButton = (Button)findViewById(R.id.button3);
        mGLSurfaceView = (GLSurfaceView)findViewById(R.id.surfaceView);

        if (detectOpenGLES20()) {
            Log.d(tag,"detectOpenGLES20");
            // Tell the surface view we want to create an OpenGL ES 2.0-compatible
            // context, and set an OpenGL ES 2.0-compatible renderer.
            mGLSurfaceView.setEGLContextClientVersion(2);
            mGLSurfaceView.setRenderer(new GLES20TriangleRenderer(this));
        } else {
            // Set an OpenGL ES 1.x-compatible renderer. In a real application
            // this renderer might approximate the same output as the 2.0 renderer.
            mGLSurfaceView.setRenderer(new TriangleRenderer(this));
        }
        Log.d(tag, "mGLSurfaceView:" + mGLSurfaceView.toString());
        mGLSurfaceView.setDebugFlags(2);
    }

    private boolean detectOpenGLES20() {
        ActivityManager am =
                (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        ConfigurationInfo info = am.getDeviceConfigurationInfo();
        return (info.reqGlEsVersion >= 0x20000);
    }

    @Override
    protected void onResume() {
        // Ideally a game should implement onResume() and onPause()
        // to take appropriate action when the activity looses focus
        super.onResume();
        mGLSurfaceView.onResume();
    }

    @Override
    protected void onPause() {
        // Ideally a game should implement onResume() and onPause()
        // to take appropriate action when the activity looses focus
        super.onPause();
        mGLSurfaceView.onPause();
    }


    public void btnOnclick(View view){
        Log.d(tag,"btnOnclick");

        EGL10 egl = (EGL10)javax.microedition.khronos.egl.EGLContext.getEGL();
        Log.d(tag, "egl:" + egl.toString());

        EGLSurface surface = egl.eglGetCurrentSurface(egl.EGL_DRAW);
        Log.d(tag, "surface:" + surface.toString());

        EGLDisplay display = egl.eglGetDisplay(egl.EGL_DEFAULT_DISPLAY);
        Log.d(tag, "display:" + display.toString());

        EGLContext context = egl.eglGetCurrentContext();
        Log.d(tag, "context:" + context.toString());

        String version = egl.eglQueryString(display, EGL10.EGL_VERSION);
        String extension = egl.eglQueryString(display, EGL10.EGL_EXTENSIONS);
        Log.d(tag, "GL version = " + version + "  extension = " + extension);

        // Query total number of configurations
        int[] totalConfigurations = new int[1];
        egl.eglGetConfigs(display, null, 0, totalConfigurations);

        // Query actual list configurations
        EGLConfig[] configurationsList = new EGLConfig[totalConfigurations[0]];
        egl.eglGetConfigs(display, configurationsList, totalConfigurations[0], totalConfigurations);
        Log.d(tag, "configurationsList = " + configurationsList[0]);

//        int widthArray[] = new int[1];
//        int heightArray[] = new int[1];
//        for (int i = 0; i < totalConfigurations[0]; i++) {
//
//            egl.eglGetConfigAttrib(display, configurationsList[i], EGL10.EGL_MAX_PBUFFER_WIDTH, widthArray);
//            egl.eglGetConfigAttrib(display, configurationsList[i], EGL10.EGL_MAX_PBUFFER_HEIGHT, heightArray);
//
//            Log.d(tag, "GL i = " + i + "  width = " + widthArray[0] + " height = " + heightArray[0]);
//        }

//        final int widthArray[] = new int[1];
//        egl.eglQuerySurface(display, surface, EGL10.EGL_WIDTH, widthArray);
//
//        final int heightArray[] = new int[1];
//        egl.eglQuerySurface(display, surface, EGL10.EGL_HEIGHT, heightArray);

        int width = mGLSurfaceView.getWidth();
        int height = mGLSurfaceView.getHeight();

        Log.d(tag, "getGL == " + context.getGL().toString());

        Bitmap bm  = getBitmapFromGL(width,height, (GL10)context.getGL());
        saveBitmap(bm);

    }

    private Bitmap getBitmapFromGL(int w, int h, GL10 gl) {
        int b[] = new int[w * (h)];
        int bt[] = new int[w * h];
        IntBuffer ib = IntBuffer.wrap(b);
        ib.position(0);
        GLES20.glReadPixels(0, 0, w, h, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, ib);
        for (int i = 0, k = 0; i < h; i++, k++) {
            for (int j = 0; j < w; j++) {
                int pix = b[i * w + j];
                int pb = (pix >> 16) & 0xff;
                int pr = (pix << 16) & 0xffff0000;
                int pix1 = (pix & 0xff00ff00) | pr | pb;
                bt[(h - k - 1) * w + j] = pix1;
            }
        }
        return Bitmap.createBitmap(bt, w, h, Bitmap.Config.ARGB_8888);
    }


    public void saveBitmap(Bitmap bitmap) {
        Log.d(tag, "保存图片");

        String state = Environment.getExternalStorageState();
        Log.d(tag, "state == " + state);
        if (Environment.MEDIA_SHARED.equals(state)) {
            // Sd card has connected to PC in MSC mode
        }

        String extPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
        File f = new File(extPath, "sc.png");
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
            Log.d(tag, "已经保存");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

